package com.doraemon.module.buyer.service.impl;

import com.doraemon.module.buyer.dao.OrderDetailDao;
import com.doraemon.module.buyer.dao.OrderMasterDao;
import com.doraemon.module.buyer.dto.CartDTO;
import com.doraemon.module.buyer.dto.OrderDTO;
import com.doraemon.module.buyer.entity.OrderDetail;
import com.doraemon.module.buyer.entity.OrderMaster;
import com.doraemon.module.buyer.entity.ProductInfo;
import com.doraemon.enums.OrderStateEnum;
import com.doraemon.enums.PayStateEnum;
import com.doraemon.enums.ResultEnum;
import com.doraemon.common.exception.SellException;
import com.doraemon.module.buyer.service.OrderService;
import com.doraemon.module.buyer.service.ProductInfoService;
import com.doraemon.utils.KeyUtils;
import com.doraemon.utils.OrderMaster2OrderDTOConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author doraemon
 * @date 2017/9/14
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private OrderMasterDao orderMasterDao;

    @Autowired
    private OrderDetailDao orderDetailDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO create(OrderDTO orderDTO) {
        //生成随机的OrderId
        String orderId = KeyUtils.getUniqueKey();
        orderDTO.setOrderId(orderId);
        //订单金额
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        List<OrderDetail> orderDetails = new ArrayList<>();
        //获取订单商品的价格，并计算金额
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = productInfoService.findOne(orderDetail.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_FOUND);
            }
            //算出商品单项的金额
            orderAmount = productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);
            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetail.setDetailId(KeyUtils.getUniqueKey());
            //收集订单详情
            orderDetails.add(orderDetail);
        }
        //订单写入数据库
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStateEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStateEnum.WAIT.getCode());
        orderMasterDao.save(orderMaster);
        //订单详情写入数据库
        orderDetailDao.save(orderDetails);
        //减库存
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.decreaseStock(cartDTOList);
        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster orderMaster = orderMasterDao.findOne(orderId);
        if (orderMaster == null) {
            throw new SellException(ResultEnum.ORDERMASTER_NOT_EXIST);
        }
        List<OrderDetail> orderDetails = orderDetailDao.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetails)) {
            throw new SellException(ResultEnum.ORDERDETIL_NOT_EXIST);
        }
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetails);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String openId, Pageable pageable) {
        Page<OrderMaster> orderMasterList = orderMasterDao.findByBuyerOpenid(openId, pageable);

        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterList.getContent());

        return new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterList.getTotalElements());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO cancle(OrderDTO orderDTO) {
        //判断订单状态
        if (!Objects.equals(orderDTO.getOrderStatus(), OrderStateEnum.NEW.getCode())) {
            log.error("【删除订单】订单状态错误(不为新下单),orderId={},orderState={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATE_ERROR);
        }
        //修改订单状态
        orderDTO.setOrderStatus(OrderStateEnum.CANCLE.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterDao.save(orderMaster);
        if (updateResult == null) {
            log.error("【删除订单】订单状态更新错误,orderMaster{}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        //加库存
        List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
        if (CollectionUtils.isEmpty(orderDetailList)) {
            log.error("【删除订单】订单中不存在商品详情,orderId={},orderState={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDERDE_DETATL_EMPTY);
        }
        List<CartDTO> cartDTOList = orderDetailList.stream()
                .map(orderDetail -> new CartDTO(orderDetail.getProductId(), orderDetail.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.increaseStock(cartDTOList);
        //需要退款的退款
        //TODO 需要退款的退款
        return orderDTO;
    }

    @Override
    public OrderDTO finished(OrderDTO orderDTO) {
        if (!orderDTO.getOrderStatus().equals(OrderStateEnum.NEW.getCode())) {
            log.error("【完成订单】订单状态错误(不为新下单),orderId={},orderState={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDERMASTER_NOT_EXIST);
        }
        orderDTO.setOrderStatus(OrderStateEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);

        OrderMaster updateResult = orderMasterDao.save(orderMaster);
        if (updateResult == null) {
            log.error("【完成订单】订单状态更新错误,orderMaster{}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    public OrderDTO paid(OrderDTO orderDTO) {
        //判读订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStateEnum.NEW.getCode())) {
            log.error("【订单支付】订单状态错误,orderId={},orderState={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATE_ERROR);
        }
        //判断支付状态
        if (!orderDTO.getPayStatus().equals(PayStateEnum.WAIT.getCode())) {
            log.error("【订单支付】订单支付状态错误,orderId={},orderPayState={}", orderDTO.getOrderId(), orderDTO.getPayStatus());
            throw new SellException(ResultEnum.ORDER_PATSTATE_ERROR);
        }
        //修改支付状态

        //TODO 支付
        return orderDTO;
    }
}
